import json
import random
import re

from django import http
from django.shortcuts import render

# Create your views here.
from aijia_house.settings.dev import logger
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from libs.captcha.captcha import captcha
from libs.yuntongxun.ccp_sms import CCP


class Captcha(View):
    """图形验证码"""

    def get(self, request):
        # 获取参数
        cur = request.GET.get("cur")  # 当前图片验证码UUID
        pre = request.GET.get("pre")  # 前一个图片验证码UUID
        # 如果当前图形验证码是空，返回错误
        if cur is None:
            return http.JsonResponse({'errno': 4103, 'errmsg': "参数错误"})

        # 生成图片验证码
        text, image = captcha.generate_captcha()
        print(text)
        # 保存图形验证码到redis
        redis_conn = get_redis_connection('verify_code')
        if pre:
            # 删除之前存储的验证码图片
            redis_conn.delete("image_%s" % pre)
        redis_conn.setex("image_%s" % cur, 300, text)

        # 4. 返回验证码图片
        return http.HttpResponse(image, content_type='image/jpg')


class SMSVerification(View):
    """短信验证码"""
    def post(self,request):
        # 接收参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")
        image_code = data_dict.get("image_code")
        image_code_id = data_dict.get("image_code_id")

        # 校验参数
        if not all([image_code, image_code_id ,mobile]):
            return http.JsonResponse({'errno': 4103,'errmsg': '缺少必传参数'})
        # 判断手机号格式是否正确
        if not re.match("^1[3578][0-9]{9}$", mobile):
            return http.JsonResponse({'errno': 4103, 'errmsg': "手机号格式不正确"})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 提取图形验证码
        image_code_server = redis_conn.get('image_%s' % image_code_id)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'errno': 4103,'errmsg': '图形验证码失效'})
        # 如果取出了值，删除redis中的图形码
        if image_code_server:
            redis_conn.delete('image_%s' % image_code_id)
        # 对比图形验证码，redis中存放着是二进制
        # bytes 转字符串
        image_code_server = image_code_server.decode()
        # 转小写后比较
        if image_code.lower() != image_code_server.lower():
            return http.JsonResponse({'errno': 4103,'errmsg': '输入图形验证码有误'})
        # 4.1 校验该手机是否已经注册
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = None  # 如果查询时出现错误，也需要给user初始化，如果不初始化，会报未定义的异常
            logger.error(e)
        if user:
            return http.JsonResponse({'errno': 4103, 'errmsg': "该手机已被注册"})
        # 生成短信验证码：生成6位数验证码
        # 或：random.randint(100000,999999)
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)

        # 保存短信验证码
        # 短信验证码有效期，单位：300秒
        redis_conn.setex('sms_%s' % mobile,300,sms_code)
        # 9. 发送短信验证码
        # 短信模板
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        print('短信验证码:', sms_code)

        # 响应结果
        return http.JsonResponse({'errno': 0,'errmsg': '发送短信成功'})